<template>
  <div class="pa30 pb100" style="padding-top: 20px;">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="用户资料" name="first">
        <component
          is="userInfoForm"
          v-if="userInfoData"
          ref="first"
          :list="userInfoData"
          @callBack="callBack"
        />
      </el-tab-pane>
      <el-tab-pane label="用户内容" name="second">
        <component is="userContentList" ref="second" />
      </el-tab-pane>
      <el-tab-pane label="使用轨迹" name="third">
        <component is="trackVue" ref="third" />
      </el-tab-pane>
      <el-tab-pane label="操作日志" name="fourth">
        <div class="infinite-list-wrapper" style="overflow:auto; height: 500px; ">
          <!-- {{ operationLogList }} -->
          <ul
            v-if="operationLogList"
            v-infinite-scroll="load"
            class="list pa30"
            infinite-scroll-disabled="disabled"
          >
            <li
              v-for="(item, index) in operationLogList"
              :key="index"
              class="list-item line-height30"
            >
              <span>{{ item.createTime }}</span>
              <span>{{ item.sysEnum }}</span>
              <span>{{ item.des }}</span>
            </li>
          </ul>
          <p v-if="loading">加载中...</p>
          <p v-if="noMore">没有更多了</p>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div v-if="userInfoData && userInfoData.type === 'TEACHER'" class="btu-bottom-fixed">
      <el-button type="primary" @click="onSubmit">保存修改</el-button>
      <el-button
        v-if="userInfoData && userInfoData.teacher && userInfoData.teacher.isFamous"
        type="success"
        @click="onCertification"
      >取消认证</el-button>
      <el-button v-else type="success" @click="onCertification">认证为名师</el-button>

      <el-button
        v-if="userInfoData && userInfoData.status === 'ENABLE'"
        type="danger"
        @click="onDisable"
      >禁用用户</el-button>
      <el-button v-else type="warning" @click="onDisable">恢复用户</el-button>

      <!-- <el-button type="danger" @click="onDelete">删除用户</el-button> -->
    </div>
    <div v-else class="btu-bottom-fixed">
      <el-button type="primary" @click="onSubmit">保存修改</el-button>
      <el-button
        v-if="userInfoData && userInfoData.status === 'ENABLE'"
        type="danger"
        @click="onDisable"
      >禁用用户</el-button>
      <el-button
        v-if="userInfoData && userInfoData.status === 'DISABLE'"
        type="warning"
        @click="onDisable"
      >恢复用户</el-button>
      <!-- <el-button type="danger" @click="onDelete">删除用户</el-button> -->
    </div>
  </div>
</template>
<script>
import { default as userInfoForm } from './user-info-form/form';
import { default as userContentList } from './user-content-list/list';
import { default as trackVue } from './track/track';
import { getUserInfo, findPage, updateUserInfo, setFamous, setUserStatus } from '@/api/users';
import { getTimes } from '@/utils/time';

export default {
  name: 'UserDetail',
  components: {
    userInfoForm,
    userContentList,
    trackVue
  },
  data () {
    return {
      activeName: 'first',
      value1: '',

      userInfoData: null,

      loading: false,
      operationLogList: [], // 操作日志列表
      operationLogTotal: null, // 总页数
      findPageQuery: {
        condition: {
          sysEnums: ['WX', 'PC'],
          targetId: null,
          userId: this.$route.query.param
        },
        pager: {
          page: 1,
          pageSize: 10
        }
      }
    };
  },
  computed: {
    noMore () {
      return this.operationLogList.length >= this.operationLogTotal;
    },
    disabled () {
      return this.loading || this.noMore;
    }
  },
  created () {
    this.init();
    // this.getUserDetail()
  },
  methods: {
    load () {
      if (this.operationLogList.length < this.operationLogTotal) {
        this.findPageQuery.pager.page += 1;
        this.getFindPage();
      }
    },
    handleClick (tab, event) {
      console.log('当前tab索引:', tab.index, this.activeName);
      // console.log(tab, event)
    },
    async init () {
      await this.getUserDetail();
      await this.getFindPage();
    },

    // 获取用户信息
    getUserDetail () {
      getUserInfo(this.$route.query.param)
        .then(res => {
          // console.log(res.data)
          this.userInfoData = res.data;
        })
        .catch(error => { });
    },

    // 获取操作日志
    getFindPage () {
      this.loading = true;
      findPage(this.findPageQuery)
        .then(res => {
          // console.log(res.data)
          this.operationLogList = this.operationLogList.concat(res.data.records);
          this.operationLogTotal = res.data.total;
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    },

    callBack (obj) {
      console.log('userInfoData', obj);
      this.userInfoData = obj;
    },
    //
    onSubmit () {
      console.log(this.userInfoData);

      var majorCodes = this.userInfoData.normalStudent.majors && this.userInfoData.normalStudent.majors.length > 0 ? this.userInfoData.normalStudent.majors[this.userInfoData.normalStudent.majors.length - 1] : '';

      var studentCertValid;
      if (this.userInfoData.normalStudent && this.userInfoData.normalStudent.studentCertValid) {
        studentCertValid = new Date(this.userInfoData.normalStudent.studentCertValid).getTime();
        studentCertValid = getTimes(studentCertValid);
      } else {
        studentCertValid = null;
      }

      var areaCode = '';
      if (this.userInfoData.org.area && this.userInfoData.org.area.districtCode) {
        areaCode = this.userInfoData.org.area.districtCode;
      } else if (this.userInfoData.org.area && this.userInfoData.org.area.cityCode) {
        areaCode = this.userInfoData.org.area.cityCode;
      } else if (this.userInfoData.org.area && this.userInfoData.org.area.provinceCode) {
        areaCode = this.userInfoData.org.area.provinceCode;
      } else {
        areaCode = '';
      }
      console.log('areaCode:', areaCode);
      var data = {
        avatarUrl: this.userInfoData.avatarUrl,
        email: this.userInfoData.email,
        mobileNumber: this.userInfoData.mobileNumber,
        name: this.userInfoData.name,
        // 师范生
        normalStudent: {
          focusLabelCodes: this.userInfoData.normalStudent.focusLabelCodes || null, // 其他擅长
          goodAtLabelCodes: this.userInfoData.normalStudent.goodAtLabelCodes || [], // 教学擅长
          majorCodes: majorCodes ? [majorCodes] : null, // 专业
          phaseCodes: this.userInfoData.normalStudent.phaseCodes || null, // 目标学段
          studentCertUrl: this.userInfoData.normalStudent.studentCertUrl || null, // 学生证附件
          studentCertValid: studentCertValid || null, // 学生证附件
          subjectCodes: this.userInfoData.normalStudent.subjectCodes ? this.userInfoData.normalStudent.subjectCodes : null // 学生证附件
        },
        org: {
          areaCode: areaCode,
          school: this.userInfoData.org.school || null,
          schoolType: this.userInfoData.org.schoolType || null
        },
        // 教师
        teacher: {
          focusLabelCodes: this.userInfoData.teacher.focusLabelCodes || null, // 其他擅长
          goodAtLabelCodes: this.userInfoData.teacher.goodAtLabelCodes || [], // 教学擅长
          isFamous: this.userInfoData.teacher.isFamous, // 是否认证为名师
          phaseCode: this.userInfoData.teacher.phaseCodes || null, // 学段
          subjectCodes: this.userInfoData.teacher.subjectCodes ? [this.userInfoData.teacher.subjectCodes] : null, // 学科
          teacherCertCode: this.userInfoData.teacher.teacherCertCode, // 资格证编号
          teacherCertType: this.userInfoData.teacher.teacherCertType, // 任教学段
          teacherCertUrl: this.userInfoData.teacher.teacherCertUrl, // 教师资格证照片url
          teacherTitle: this.userInfoData.teacher && this.userInfoData.teacher.teacherTitle ? this.userInfoData.teacher.teacherTitle : null, // 职称证类型
          titleCertCode: this.userInfoData.teacher.titleCertCode, // 职称编号
          titleCertUrl: this.userInfoData.teacher.titleCertUrl, // 职称编号
          trainSpecialityCodes: this.userInfoData.teacher.trainSpecialityCodes || [] // 培训擅长
        },
        userId: this.userInfoData.userId,
        zyzUrl: this.userInfoData.zyzUrl // 职业照
      };
      if (this.userInfoData.type === 'STUDENT') {
        data.org.schoolType = null;
        data.teacher.goodAtLabelCodes = null;
      }
      console.log('参数:', data);
      updateUserInfo(data).then(res => {
        console.log(res.data);
        this.$message({
          message: '保存成功',
          type: 'success'
        });
      });
    },
    // 名师认证
    onCertification () {
      console.log(this.userInfoData);
      var isFamous = !!(this.userInfoData && this.userInfoData.teacher && this.userInfoData.teacher.isFamous);

      var msg = !isFamous ? '是否需要认证名师！' : '是否需要取消名师！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          setFamous({
            isFamous: !isFamous,
            userId: this.userInfoData.userId
          }).then(res => {
            console.log(res.data);
            if (!isFamous) {
              this.$message({
                message: '认证成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: '取消成功',
                type: 'success'
              });
            }
            this.getUserDetail();
          });
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    // 禁用用户
    onDisable () {
      console.log(this.userInfoData.status);
      var userStatus = this.userInfoData.status === 'DISABLE' ? 'ENABLE' : 'DISABLE';
      console.log('userStatus:', userStatus);
      var msg = userStatus === 'DISABLE' ? '是否禁用该用户！' : '是否恢复该用户！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          setUserStatus({
            userStatus: userStatus,
            userId: this.userInfoData.userId
          }).then(res => {
            console.log(res.data);
            if (userStatus === 'DISABLE') {
              this.$message({
                message: '恢复成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: '禁用成功',
                type: 'success'
              });
            }
            this.getUserDetail();
          });
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    // 删除用户
    onDelete () { }
  }
};
</script>

<style lang="scss" scoped>
.scroll-height {
  height: 500px;
  overflow-y: scroll;
}

.infinite-list-wrapper {
  .list {
    .list-item {
      line-height: 30px;
    }
  }
  p {
    text-align: center;
  }
}
</style>
